package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;
import java.time.LocalDateTime;

@RestController//controller+responseBody
@RequestMapping("/employee")
@Slf4j
public class EmployeeController {

    /*
    一定要注入接口，千万不要注入实现类，因为此时找的是一个动态代理对象
    在spring底层会针对当前这个EmployeeService 接口去生成代理，而代理，再帮我们完成事情。
     */
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")//因为要拿session，所以要request对象
    public R login(HttpServletRequest request, @RequestBody Employee employee) {
        //1.获取传入的密码，进行md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2.根据用户名查找数据库中的用户是否存在
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<Employee>();
        LambdaQueryWrapper<Employee> eq = lambdaQueryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(eq);
        if (emp == null) {
            return R.error("请注册后再登录,登录失败！");
        }
        //3.说明用户不等于空，于是取出他的密码与出入密码进行对比，看是否相等
        String dataPassword = emp.getPassword();//数据库中的密码
        if (!dataPassword.equals(password)) {
            return R.error("用户名或者密码错误！");
        }
        //4.看是否为禁用状态,0表示禁用
        if (emp.getStatus() == 0) {
            return R.error("该用户已经被禁用，请联系管理员！");
        }
        //6、登录成功，将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("employee", emp.getId());
        //7.把敏感信息设置为null，如密码
        emp.setPassword(null);
        return R.success(emp);
    }

    @PostMapping("/logout")
    public R logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return R.success(null);
    }

    @PostMapping
    public R save(@RequestBody Employee employee, HttpServletRequest request) {
        //1.为员工设置一个默认密码,并md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        log.info("员工密码为" + employee.getPassword());
        log.info("localDateTime:" + LocalDateTime.now());

        //2.设置创建时间
        employee.setCreateTime(LocalDateTime.now());
        //3.设置更新时间
        employee.setUpdateTime(LocalDateTime.now());
        //4.设置创建人和修改人
        Long empID = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(empID);
        employee.setUpdateUser(empID);

        //插入到数据库中
        employeeService.save(employee);
        return R.success(null);
    }

    @GetMapping("/page")
    public R page(int page, int pageSize, String name) {
        //1.构建分页构造器，此时进自动计算总页数等.
        Page pageInfo = new Page(page, pageSize);
        //2.设置条件,进行条件查询

        LambdaQueryWrapper<Employee> elqw = new LambdaQueryWrapper<>();
        if (name != null) {
            elqw.like(Employee::getName, name);//设置模糊查询
        }
        elqw.orderByDesc(Employee::getUpdateTime);//设置排序条件
        employeeService.page(pageInfo, elqw);
        return R.success(pageInfo);
    }

    /*
    丢失精度-->前端对于非常长的数字如果是 非 varchar类型，此时不能超过一定长度，如果超过了一定长度，前端会把这个数据精度舍弃
    解决办法：1.是直接将实体类的id修改成string
    2.是在进行给前端响应json时，把数据响应成json，但是实体类上还是long。
     */
    @PutMapping
    public R updateEmp(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("修改put中的employeeId为：{} " , employee.getId());
        //1.看是谁在操作
        employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));
        //2.更新操作时间
        employee.setUpdateTime(LocalDateTime.now());
        //3.进行更新操作
        employeeService.updateById(employee);

        return R.success(null);
    }

    @GetMapping("/{id}")
    public R queryEmployeeById(@PathVariable Long id){
        Employee emp = employeeService.getById(id);//根据id进行查询对象
        if (emp!=null){
            //处理密码
            emp.setPassword(null);
            return R.success(emp);
        }
      return R.error("没有查询到对应员工信息！");
    }


}
